package com.hqyj.javaSpringCloudAccount.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.hqyj.entity.account.Menu;
import com.hqyj.javaSpringCloudAccount.dao.MenuDao;
import com.hqyj.javaSpringCloudAccount.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Description: Menu Service Impl
 * @author HymanHu
 * @date 2021-08-05 16:42:46
 */
@Service
public class MenuServiceImpl implements MenuService {
	
	@Autowired
	private MenuDao menuDao;

	@Override
	public List<Menu> getAllMenus() {
		List<Menu> allMenus = Optional.ofNullable(menuDao.getAllMenus()).orElse(Collections.emptyList());
		List<Menu> rootMenus = allMenus.stream()
			.filter(item -> item.getParentId() == 0)
			.collect(Collectors.toList());
		findSubItems(allMenus, rootMenus);
		return rootMenus;
	}
	
	// 递归封装多级菜单
	private void findSubItems(List<Menu> allMenus, List<Menu> rootMenus) {
		rootMenus.stream().forEach(item -> {
			List<Menu> subItems = new ArrayList<Menu>();
			allMenus.stream().forEach(it -> {
				if (it.getParentId() == item.getId()) {
					subItems.add(it);
				}
			});
			findSubItems(allMenus, subItems);
			item.setSubItems(subItems);
		});
	}

	@Override
	public List<Menu> getMenusByUserId(int userId) {
		List<Menu> allMenus = Optional
				.ofNullable(menuDao.getMenusByUserId(userId))
				.orElse(Collections.emptyList());
		List<Menu> rootMenus = allMenus.stream()
			.filter(item -> item.getParentId() == 0)
			.collect(Collectors.toList());
		findSubItems(allMenus, rootMenus);
		return rootMenus;
	}

}
